/*

Copyright (c) 2003, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include <iostream>
#include <fstream>
#include <iterator>
#include <exception>

#include <pthread.h>
#include <string>
#include <ncurses.h>
#include <cstdlib>
#include "dispatcher.h"
#include "backup_server_connection.h"

#include "libtorrent/entry.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/session.hpp"

using namespace libtorrent;
torrent_handle torrent_h;
session s;
        
dispatcher disp;
backup_server_connection connection("cowboycoders.se",
                                    "22234",
                                    "big_buck_bunny",
                                    disp,
                                    10);

void on_download_complete(backup_server_connection::request req,
                          char* data,
                          size_t num_bytes)
{
    /*std::cout << "received " << num_bytes << " bytes of data"
              << " | piece_size: " << req.piece_size 
              << " | index: " << req.index
              << " | count: " << req.count
              << std::endl;
    */
    // You are now the owner of the data buffer, with the
    // responsibility to delete it when done!
    torrent_h.add_piece(req.index,data,0);
    torrent_h.add_piece(req.index,data,0);

    delete [] data;
}

int iter;
void check_torrent_status(torrent_handle& th, 
                          std::vector<partial_piece_info>& info) 
{
    for(int loop_count = 0; loop_count < 4; ++loop_count)
    {
        ++iter;
        move(0,0);
        //std::cout << std::string(90,'\n') << color(lightgray); //Clear screen.
        //ss << std::string(90,'\n');
        
        //std::cout << std::endl << "is_downloaded: " << th.
        printw("\nAntal Peers: %i", s.status().num_peers);
        printw("\nAntal unchoked: %i", s.status().num_unchoked);
        printw("\nAntal connections: %i", s.num_connections());
        printw("\ncurrent dl rate(kb): %f", s.status().download_rate/1024);
        printw("\ncurrent ul rate(kb): %f", s.status().upload_rate/1024);
        printw("\nChunk size(kb): %i",th.get_torrent_info().piece_length()/1024);
        printw("\nTotal downloaded(mb): %i", s.status().total_download/1024/1024);

        th.get_download_queue(info);
        //Print all in dl-queue.
        /*std::cout << std::endl << "Info size: " << info.size();
        for(int i = 0; i < info.size(); ++i) {
            std::cout << std::endl << "Piece_index: " << info[i].piece_index;
            std::cout << std::endl << "State: " << info[i].piece_state;
        }*/
        
        bool set_prios = true;
        if(set_prios) {
            //Print all prios.
            int late_pieces = 0;
            std::vector<int> prios = th.piece_priorities();
            printw("\nAntal chunks: %i", prios.size());
            bitfield bf = th.status().pieces;
            printw("\nPrios: \n");
            int dling = -1;
            for(int i = 0; i < prios.size(); ++i) {
                //Check if downloading.
                for(std::vector<partial_piece_info>::iterator it = info.begin(); it != info.end(); ++it) {
                    if(i==(*it).piece_index) {
                        dling = (*it).piece_state;
                        break;
                    } else {
                        dling = -1;
                    }
                }
                int color = 0; //White
                if(iter == i) {
                    color = 1; //Red

                    //Requests each piece 2 times from the backup server, BUG?
                    //for(int j = 0; j < 2; ++j){
                        backup_server_connection::request
                            request(th.get_torrent_info().piece_length(),i-1,1);
                         connection.send(request, on_download_complete);
                    //}

                    attron(COLOR_PAIR(color));
                    printw(">");
                    attroff(COLOR_PAIR(color));
                    color = 0; //white
                }
                if(bf[i]) { //We have it.
                    color = 2; //green
                } else if(dling > 0) {
                    if(dling == 3) color = 5; //white on green.
                    if(dling == 2) color = 4; //balck on white.
                    if(dling == 1) color = 6; //black on red.
                }/* else if(!bf[i] && t[0].piece_priority(i) == 0){ //Is late.
                    color = 3; //blue
                    late_pieces++;
                }*/ else {
                    color = 0; //White
                }
                attron(COLOR_PAIR(color));
                printw("%i",prios[i]);
                attroff(COLOR_PAIR(color));
            }
            printw("\nLate pieces: %i", late_pieces);
            printw("\nIter: %i", iter);


            //Set new priorities.
            if(iter > 0) {
                for(int i = iter+5, j = 7; j > 0; i+=5, --j) {
                    if(j==7) {
                        th.piece_priority(i-5,0);
                        th.piece_priority(i-4,0);
                        th.piece_priority(i-3,0);
                        th.piece_priority(i-2,0);
                        th.piece_priority(i-1,0);
                        th.piece_priority(i,0);
                    }
                    th.piece_priority(i+5,j);
                    th.piece_priority(i+6,j);
                    th.piece_priority(i+7,j);
                    th.piece_priority(i+8,j);
                    th.piece_priority(i+9,j);

                }
                //th.set_sequential_download(false);
            }
        } else {
            attron(COLOR_PAIR(1));
            printw("\nOnly seeding!");
            attroff(COLOR_PAIR(1));
        }

        refresh();

    }
    sleep(1);


}

int main(int argc, char* argv[])
{
#if BOOST_VERSION < 103400
	namespace fs = boost::filesystem;
	fs::path::default_name_check(fs::no_check);
#endif

	if (argc != 2)
	{
		std::cerr << "usage: ./simple_client torrent-file\n"
			"to stop the client, press return.\n";
		return 1;
	}

#ifndef BOOST_NO_EXCEPTIONS
	try
#endif
	{

        //Add torrent
		s.listen_on(std::make_pair(6881, 6889));
        s.set_download_rate_limit(400*1024);
		add_torrent_params p;
		p.save_path = "./";
		p.ti = new torrent_info(argv[1]);
        p.storage_mode = storage_mode_allocate;
		s.add_torrent(p);

        session_settings pref;
        pref.unchoke_interval = 1;
        s.set_settings(pref);

        //ncurses.
        initscr(); //Init screen.
        start_color();
        init_pair(0, COLOR_WHITE, COLOR_BLACK); //white on black. normal.
        init_pair(1, COLOR_RED, COLOR_BLACK); //red on black. Cursor.
        init_pair(2, COLOR_GREEN, COLOR_BLACK); //green on black.
        init_pair(3, COLOR_BLUE, COLOR_BLACK); //blue on black.
        init_pair(4, COLOR_BLACK, COLOR_WHITE); //black on white.
        init_pair(5, COLOR_WHITE, COLOR_GREEN); //white on green.
        init_pair(6, COLOR_BLACK, COLOR_RED); //black on red.


        std::vector<torrent_handle> t;
        std::vector<partial_piece_info> info;
        t = s.get_torrents();
        torrent_h = t[0];
        std::vector<int> ve;
         
        for(int i = 0; i < 20; ++i) {
            ve.push_back(7);
        }
        //t[0].prioritize_pieces(ve);

        t[0].set_sequential_download(true); //Set sequential dl.

        printw("Starting up...");
        refresh();

        bool skip = true;
        while(s.status().download_rate/1024 < 100 && !skip) {
            move(0,0);
            printw("\nAntal Peers: %i", s.status().num_peers);
            printw("\nAntal unchoked: %i", s.status().num_unchoked);
            printw("\nAntal connections: %i", s.num_connections());
            printw("\ncurrent dl rate(kb): %f", s.status().download_rate/1024);
            printw("\ncurrent ul rate(kb): %f", s.status().upload_rate/1024);
            printw("\nTotal downloaded(mb): %i", s.status().total_download/1024/1024);
            refresh();
        }
        t[0].set_sequential_download(false); //Set sequential dl.

        iter = 0;
        while(true) {
            disp.post(boost::bind(&check_torrent_status, t[0], info));
            sleep(1);
        }
        endwin(); //End ncurses.

		// wait for the user to end
		/*char a;
		std::cin.unsetf(std::ios_base::skipws);
		std::cin >> a;*/
	}
#ifndef BOOST_NO_EXCEPTIONS
	catch (std::exception& e)
	{
  		std::cerr << "exception: " << e.what() << std::endl;
	}
#endif
	return 0;
}

